package com.example.paging3samples.network

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.paging3samples.network.model.anime.Post
import javax.inject.Inject
import okio.IOException
import retrofit2.HttpException

class PostsPagingSource @Inject constructor(private val apiService: ApiService): PagingSource<Int, Post>() {
    override fun getRefreshKey(state: PagingState<Int, Post>): Int? {
        return state.anchorPosition
    }
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Post> {
        val pageNumber = params.key ?: 1
        return try {
            val pageResult = apiService.getPosts(pageNumber)
            val posts = pageResult.posts


            LoadResult.Page(
                data = posts,
                prevKey = if (pageResult.page_number == 1) null else pageResult.page_number - 1,
                nextKey = if (pageResult.page_number == pageResult.max_pages) null else pageNumber + 1
            )
        } catch (exception: IOException) {
            return LoadResult.Error(exception)
        } catch (exception: HttpException) {
            return LoadResult.Error(exception)
        }
    }
}